/**
 * Copyright (C) Olafur Gauti Gudmundsson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.solrom.dao;

import java.io.IOException;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;
import org.jcrom.Jcrom;
import org.jcrom.dao.AbstractJcrDAO;
import org.solrom.IndexFieldMappingException;
import org.solrom.Solrom;

/**
 * An abstract extension of the AbstractJcrDAO class. This should be extended
 * for specific entity implementations.
 * This class overrides all methods in AbstractJcrDAO that write to the JCR
 * repository, so that the object can be indexed (or deleted from the index)
 * on write events. The class also adds methods for searching and object mapping
 * without going to the JCR repository.
 *
 * @author Olafur Gauti Gudmundsson
 */
public abstract class AbstractIndexingDAO<T> extends AbstractJcrDAO<T> {
	
	protected final SolrServer solrServer;
	protected final Solrom solrom;

	public AbstractIndexingDAO( Class<T> entityClass, Jcrom jcrom, Solrom solrom ) {
        this(entityClass, jcrom, null, solrom);
	}

	public AbstractIndexingDAO( Class<T> entityClass, Jcrom jcrom, SolrServer solrServer, Solrom solrom ) {
		super(entityClass, jcrom);
		this.solrServer = solrServer;
		this.solrom = solrom;
	}
    
    public AbstractIndexingDAO( Class<T> entityClass, Session session, Jcrom jcrom, SolrServer solrServer, Solrom solrom ) {
		super(entityClass, session, jcrom);
		this.solrServer = solrServer;
		this.solrom = solrom;
	}
	
	public AbstractIndexingDAO( Class<T> entityClass, Session session, Jcrom jcrom, String[] mixinTypes, SolrServer solrServer, Solrom solrom ) {
		super(entityClass, session, jcrom, mixinTypes);
		this.solrServer = solrServer;
		this.solrom = solrom;
	}
    
    protected SolrServer getSolrServer() {
        return solrServer;
    }
    
    public void index( T entity ) {
		try {
			SolrInputDocument inputDoc = solrom.toDocument(entity);
			getSolrServer().add(inputDoc);
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		}
    }

	@Override
	public T create(String parentNodePath, T entity) {
		T object = super.create(parentNodePath, entity);
		
		try {
			SolrInputDocument inputDoc = solrom.toDocument(object);
			getSolrServer().add(inputDoc);
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		}
		
		return object;
	}

	@Override
	protected String update(Node node, T entity, String childNodeFilter, int maxDepth) {
		String name = super.update(node, entity, childNodeFilter, maxDepth);
		
		try {
			SolrInputDocument inputDoc = solrom.toDocument(entity);
			getSolrServer().add(inputDoc);
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not index object", e);
		}
		
		return name;
	}

	@Override
	public void remove(String path) {
		T obj = get(path);
		Object indexId = solrom.getId(obj);
		super.remove(path);
		try {
			getSolrServer().deleteById(indexId.toString());
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		}
	}

	@Override
	public void removeByUUID(String uuid) {
		T obj = loadByUUID(uuid);
		Object indexId = solrom.getId(obj);
		super.removeByUUID(uuid);
		try {
			getSolrServer().deleteById(indexId.toString());
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		}
	}

	@Override
	protected void restoreVersion(Node node, String versionName, boolean removeExisting ) {
		super.restoreVersion(node, versionName, removeExisting);
		
		try {
			SolrInputDocument inputDoc = solrom.toDocument(jcrom.fromNode(entityClass, node));
			getSolrServer().add(inputDoc);
			getSolrServer().commit();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		} catch ( IOException e ) {
			throw new IndexFieldMappingException("Could not remove object from index", e);
		}
	}
	
	
	/**
	 * Perform a search using the Solr server, and then map all the documents
	 * returned to objects (without going to the JCR repository). Useful for
	 * lightweight lists (faster than going to the repository).
	 * 
	 * @param query the query to execute
	 * @return a list of objects mapped from the resulting SolrDocument list
	 */
	public List<T> search( SolrQuery query ) {
		for ( String fieldName : solrom.getQueryFieldNames(entityClass) ) {
			query.addField(fieldName);
		}
		try {
			QueryResponse response = getSolrServer().query( query );
			return solrom.fromDocumentList(entityClass, response.getResults());
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not search", e);
		}
	}
    
    public long getResultSize( SolrQuery query ) {
        try {
            QueryResponse response = getSolrServer().query( query );
            return response.getResults().getNumFound();
		} catch ( SolrServerException e ) {
			throw new IndexFieldMappingException("Could not search", e);
		}
    }
	
}
